package boun.swe.bob.authentication;

import boun.swe.bob.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * This class handles the authentication actions
 */
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    /**
     * Corresponds to user table in database
     */
    @Autowired
    private UserDao userDao;

    /**
     * This method handles the successful authentication
     *
     * Creates a session for the user
     * Redirects to users home page
     * @param request Variable type of HttpServletRequest
     * @param response Variable type of HttpServletResponse
     * @param authentication Variable type of Authentication
     * @throws IOException
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        boun.swe.bob.entities.User user = userDao.findByUsername(request.getParameter("j_username"));
        request.getSession().setAttribute("user", user);
        response.sendRedirect("/bob-web/service/homePage.htm");
    }


}
